/*
 * file_fd_mmap_ex_f.cpp
 *
 *  Created on: Jul 3, 2012
 *      Author: lucid
 */

#include "comm_lib_f.h"
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
#include "file_fd_mmap_f.h"

//will finish it later
//how to allocate the memory dynamic and effective is very important


filefd_mmapf_t::filefd_mmapf_t()
	:filefdf_t()
{
	m_pData = 0;
}

filefd_mmapf_t::~filefd_mmapf_t()
{
	close();
}

ssize_t filefd_mmapf_t::write(ssize_t iPos,const void* pData,ssize_t iLen)
{
	if (iPos + iLen > get_len())
		return 0;
	memcpy(m_pData+iPos,pData,iLen);
	fsync(m_fd);
	return iLen;
}

ssize_t filefd_mmapf_t::read(ssize_t iPos,void* pData,ssize_t iLen)
{
	if (iPos + iLen > get_len())
		return 0;
	memcpy(pData,m_pData+iPos,iLen);
	return iLen;
}

int filefd_mmapf_t::close()
{
	close_map();
	return filefdf_t::close();
}

void* filefd_mmapf_t::get_addr()
{
	return m_pData;
}

int filefd_mmapf_t::open_map(U32 dwLen)
{
	close_map();
	set_len(dwLen);
	m_pData = (U8*)mmap(0,dwLen,PROT_READ|PROT_WRITE,MAP_SHARED,m_fd,0);
	return (m_pData != 0) ? RETURN_SUCCESS_F : RETURN_ERROR_F;
}

int filefd_mmapf_t::close_map()
{
	if(!m_pData)
		return RETURN_ERROR_F;
	int iRet = munmap(m_pData,get_len());
	if (0 == iRet) {
		m_pData = 0;
	}
	return (0 == iRet) ? RETURN_SUCCESS_F : RETURN_ERROR_F;
}







